import React, { useState, useEffect, useRef } from 'react'
import { NavBar, InfiniteScroll } from 'antd-mobile'
import { AppstoreOutline } from 'antd-mobile-icons'
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
import { useNavigate } from 'react-router-dom'
import style from '../styles/houserent.module.css'
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3000'

export default function House() {
    const navigate = useNavigate()
    const [list, setList] = useState([])
    const [show, setShow] = useState(true)
    const [page, setPage] = useState(1)
    const [pagesize, setPageSize] = useState(2)
    const [hasMore, setHasMore] = useState(true)
    const containerRef = useRef("");
    const gap = 9;
    const [active, setActive] = useState(0)

    useEffect(() => {
        getAllHouses()
    }, [])

    const back = () => {
        navigate('/home')
    }

    const loadMore = async () => {
        let data = await axios.get('/lyc/gethouserent', { params: { page, pagesize } }).then(async (res) => {
            const itemsNodes = containerRef.current.children;//main_item
            Array.from(itemsNodes).forEach((item) => {
                item.style.height = 'auto';
            });
            await sleep(200)
            let { data: { data } } = res
            return data
            // setList(data)
        })
        setList((prev) => [...prev, ...data]);
        setHasMore(data.length > 0);
        setPage(page + 1);

    }
    const getAllHouses = async () => {
        setActive(0)
        let res = await axios.get('/lyc/gethouserent')
        console.log(res.data.data, 'getallhouserent');
        if (res.data.code === 200) {
            setList(res.data.data)
        }
    }
    const getZzHouses = async () => {
        setActive(1)
        try {
            const res = await axios.get('/lyc/gethouserent');
            if (res.data.code === 200) {
                const filteredData = res.data.data.filter(item => item.cate === '0');
                console.log(filteredData, '1234');
                setList(filteredData); // 更新状态变量
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    }
    const getHzHouses = async () => {
        setActive(2)
        try {
            const res = await axios.get('/lyc/gethouserent');
            if (res.data.code === 200) {
                const filteredData = res.data.data.filter(item => item.cate === '1');
                console.log(filteredData, '1234');
                setList(filteredData); // 更新状态变量
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    }
    const getQie = async () => {
        setShow(!show);
    }
    useEffect(() => {
        if (!show) {
            waterFall();
        }
    }, [show, list])

    const waterFall = () => {
        const itemsNodes = containerRef.current.children;//main_item
        const pageWidth = window.innerWidth - gap * 2;//页面宽度
        if (!itemsNodes.length) return;
        const itemWidth = itemsNodes[0]?.offsetWidth;//单个元素宽度
        const columns = Math.floor(pageWidth / itemWidth);
        const heights = []; // 存储每一列的高度
        for (let i = 0; i < itemsNodes.length; i++) {
            if (i < columns) {
                // 第一行
                itemsNodes[i].style.position = 'absolute';
                itemsNodes[i].style.top = '0px';
                itemsNodes[i].style.left = `${(itemWidth + gap) * i}px`;
                heights.push(itemsNodes[i].offsetHeight);
            } else {
                // 找到最小高度的列
                let minHeight = heights[0];
                console.log(minHeight, 'minhaeight1111111111');
                let index = 0;
                for (let j = 0; j < heights.length; j++) {
                    if (heights[j] < minHeight) {
                        minHeight = heights[j];
                        index = j;
                    }
                }
                console.log(minHeight, 'minhaeight2222222222222');
                // 设置位置
                itemsNodes[i].style.top = `${minHeight + gap}px`;
                itemsNodes[i].style.left = `${itemsNodes[index].offsetLeft}px`;

                // 更新列的高度
                heights[index] += itemsNodes[i].offsetHeight + gap;
            }
        }
    };




    useEffect(() => {
        // 监听窗口大小变化
        window.addEventListener('resize', waterFall);

        // 清理事件监听器
        return () => {
            window.removeEventListener('resize', waterFall);
        };
    }, [gap]);


    return (
        <div id={style.houserent}>
            <div className={style.top}>
                <NavBar onBack={back}>房屋租赁</NavBar>
            </div>
            <div className={style.btn}>
                <div className={style.btn_container}>
                    <button onClick={() => { getAllHouses() }} style={{ color: active === 0 ? 'red' : '' }}>全部房源</button>
                    <button onClick={() => { getZzHouses() }} style={{ color: active === 1 ? 'red' : '' }}>整租</button>
                    <button onClick={() => { getHzHouses() }} style={{ color: active === 2 ? 'red' : '' }}>合租</button>
                </div>
                <div style={{ float: 'right', marginTop: '-25px' }}><AppstoreOutline fontSize={22} onClick={() => getQie()} /></div>
            </div>
            <div className={style.main} >
                {
                    show ? <>
                        {
                            list.map((item, index) => {
                                return <div key={index} className={style.main_item} onClick={() => { navigate('/detail/' + item._id) }}>
                                    <div className={style.main_one}>
                                        <img src={item.img[0]} alt="" />
                                        <div className={style.main_item_right}>
                                            <h3>{item.title}</h3>
                                            <p style={{ fontSize: '15px', color: '#aaa' }}>面积：{item.area}平</p>
                                            <p style={{ color: 'red' }}>￥{item.price}/月</p>
                                        </div>
                                    </div>

                                </div>
                            })
                        }</> : <>
                        <div className={style.waterMain} ref={containerRef}>
                            {
                                list.map((item, index) => {
                                    return <div key={index} className={style.pull_item} onClick={() => { navigate('/detail/' + item._id) }}>
                                        <LazyLoadImage
                                            // height={"3rem"} // 统一高度  
                                            src={item.img[0]}
                                            width={"100%"}
                                            effect="blur"
                                            style={{ objectFit: "cover" }} // 设置 object-fit 和 height  
                                        />
                                        <p style={{ fontSize: '16px' }}>{item.title}</p>
                                        <p style={{ fontSize: '15px', color: '#aaa' }}>面积：{item.area}平</p>
                                        <p style={{ color: 'red' }}>￥{item.price}/月</p>
                                    </div>
                                })
                            }
                            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
                        </div>
                    </>
                }

            </div>
        </div>
    )
}
